package backup

import (
	"context"
	"fmt"
	"strings"

	"phant-operator/pkg/controller"

	batchv1 "k8s.io/api/batch/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	batchlisters "k8s.io/client-go/listers/batch/v1"
	"k8s.io/klog/v2"
)

type backupManager struct {
	deps      *controller.Dependencies
	jobLister batchlisters.JobLister
}

// NewBackupManager return backupManager
func NewBackupManager(deps *controller.Dependencies) *backupManager {
	return &backupManager{
		deps:      deps,
		jobLister: deps.JobLister,
	}
}

func (bm *backupManager) Sync(backupJobName string, job *batchv1.Job) error {

	//job.Annotations = make(map[string]string)
	//job.Status = nil
	var (
		name = backupJobName
		ns   string
	)

	ss := strings.Split(backupJobName, "/")
	if len(ss) == 2 {
		ns, name = ss[0], ss[1]
	}
	jobLabels := job.Labels
	job.Spec.Template.Labels = jobLabels
	job.Spec.Template.Annotations = job.Annotations
	jobv1 := &batchv1.Job{
		ObjectMeta: metav1.ObjectMeta{
			Name:            name,
			Namespace:       ns,
			Labels:          job.Labels,
			OwnerReferences: job.OwnerReferences,
		},
		Spec: batchv1.JobSpec{
			BackoffLimit: job.Spec.BackoffLimit,
			Template:     job.Spec.Template,
		},
	}
	//delete(job.Spec.Template.Labels, "controller-uid")
	//delete(job.Spec.Template.Labels, "batch.kubernetes.io/controller-uid")
	err := fmt.Errorf("jobs.batch \"%s\" already exists", backupJobName)
	fmt.Println(err, ":", errors.ReasonForError(err))
	_, err = bm.deps.KubeClientset.BatchV1().Jobs(ns).Create(context.TODO(), jobv1, metav1.CreateOptions{})
	if err != nil {
		fmt.Println(errors.ReasonForError(err), errors.IsAlreadyExists(err))
		klog.Errorf("err: %v", err)
		return err

	}
	return nil
}

func (bm *backupManager) getBackupJob(ns, backupJobName string) (*batchv1.Job, error) {
	job, err := bm.jobLister.Jobs(ns).Get(backupJobName)
	if !errors.IsNotFound(err) {
		return nil, fmt.Errorf("get job %s/%s failed, err: %v", ns, backupJobName, err)
	}
	klog.Errorf("failed to get job: %s", err)
	if err != nil {
		return nil, err
	}

	return job, nil
}
